/* ============================================================================= */
/*       TABLE 9 - FIRM GROWTH AND EMPLOYMENT (P2P ONLY - MATCHED SAMPLE)       */
/* ============================================================================= */

clear all

//----------------------------------------------------------------------------//
//                 STEP 1: PREPARE MATCHED SAMPLE WEIGHTS                      //
//----------------------------------------------------------------------------//

use "$output\matched_sample_nn.dta", clear
    keep siren weight
    sort siren
    quietly by siren: gen dup = cond(_N == 1, 0, _n)
    drop if dup > 1
    save "$output\matched_weights.dta", replace	

//----------------------------------------------------------------------------//
//                 STEP 2: LOAD & CLEAN UNMATCHED SAMPLE                       //
//----------------------------------------------------------------------------//

use "$output\SCR_CIB_3_months_orbis_scrapped.dta", clear

    /* Industry Merging */
    replace industry = "public" if inlist(industry, "P", "Q", "R", "S")
    replace industry = "DE" if inlist(industry, "D", "E")
    replace industry = "FL" if inlist(industry, "F", "L")

    /* Drop irrelevant industries */
    drop if inlist(industry, "A", "K", "O", "B", "DE", "0000Z")

    /* Keep observations before 2020 */
    keep if mdate < mofd(date("20200101","YMD"))

    /* Remove duplicates based on `siren`, `mdate`, `cib` */
    sort siren mdate cib
    bys siren mdate cib: gen nb = _N
    drop if nb > 1
    drop nb

    /* Generate key financial variables */
    gen lasset = log(assets)
    gen lassetfilled = log(assets_filled)
    replace investment = r12filled * assets
    gen linvestment = log(investment)
    gen rsales = r5filled
    gen lsales = log(sales)
    gen lemployment = log(employees)
    gen lcollat = log(immo_corp)
    gen loan = drawn + available
    gen collat = r_collateral

    keep lasset linvestment lsales lcollat investment rsales lemployment collat r14 siren p2p post mdate deltamonths year nesc outsideloandate date loan outsideloan rate maturity lassetfilled r_employfilled rating dettefiscta dettefouta employees r3* assets salaires_orbis r1 r_collateral_filled r5filled inventory cash dettefou creclie dettefisc otherwc

//----------------------------------------------------------------------------//
//                 STEP 3: YEARLY AGGREGATION & POST-LOAN FLAG                 //
//----------------------------------------------------------------------------//

    * Convert month data to year data
    gen year_loan = substr(outsideloandate, 1, 4)
    destring year_loan, replace
    gen delta_year = year - year_loan

    * Keep only December observations
    gen monthkeep = substr(date, 6, 2)
    keep if monthkeep == "12"

    * Define post-loan period
    gen post = year >= year_loan

    * Collapse data by firm, year, and other relevant variables
    collapse (mean) lasset linvestment lsales lcollat investment rsales lemployment collat r14 outsideloan rate maturity lassetfilled r_employfilled dettefiscta dettefouta employees r3* assets salaires_orbis r1 r_collat r5filled inventory cash dettefou creclie dettefisc otherwc, ///
        by(siren p2p year delta_year nesc post year_loan rating)

//----------------------------------------------------------------------------//
//                 STEP 4: COMPUTE PRE-TREATMENT FINANCIALS                    //
//----------------------------------------------------------------------------//

    xtset siren year
    gen assets_pre = L.assets

    * Normalize key financials by pre-treatment assets
    foreach var of varlist r3 r1 collat rsales dettefiscta dettefouta r_employfilled {
        gen `var'_pre = `var' * assets / assets_pre
    }

    foreach var of varlist inventory cash creclie dettefou dettefisc otherwc {
        gen `var'_pre = `var' / assets_pre
    }

    * Set panel structure
    xtset siren year

    * Encode rating variable
    egen ratingint = group(rating)
    replace ratingint = ratingint - 1
    replace ratingint = 13 if ratingint == 0

//----------------------------------------------------------------------------//
//                 STEP 5: MERGE MATCHED SAMPLE & APPLY WEIGHTS                //
//----------------------------------------------------------------------------//

    merge m:1 siren using "$output\matched_weights.dta"
    keep if _merge == 3
    drop _merge

    * Keep observations within [-4,4] years of the loan
    keep if delta_year >= -4 & delta_year <= 4
    replace delta_year = delta_year + 6

    * Compute Working Capital excluding `dettefou`
    gen wc_no_dettefou = inventory_pre + cash_pre + creclie_pre + otherwc_pre - dettefisc_pre

//----------------------------------------------------------------------------//
//                 STEP 6: WINSORIZE EXTREME VALUES                            //
//----------------------------------------------------------------------------//

    foreach var of varlist lasset lsales lemployment lcollat ldettefisct ldettefou r3 r1 *_pre wc* {
        su `var', d
        gen `var'_wsr = `var' if `var' > `r(p1)' & `var' < `r(p99)' & `var' !=.
        replace `var'_wsr = `r(p1)' if `var' < `r(p1)' & `var' !=.
        replace `var'_wsr = `r(p99)' if `var' > `r(p99)' & `var' !=.
    }

//----------------------------------------------------------------------------//
//                 STEP 7: REGRESSIONS                                         //
//----------------------------------------------------------------------------//

    qui eststo reg1: reghdfe lasset i1.p2p##i1.post [pweight=weight], a(i.siren i.nesc#i.year) cluster(siren) 
	estadd local firm "Y", replace 
	estadd local indyear "Y", replace  
    qui eststo reg2: reghdfe lcollat i1.p2p##i1.post [pweight=weight], a(i.siren i.nesc#i.year) cluster(siren)
	estadd local firm "Y", replace 
	estadd local indyear "Y", replace  
    qui eststo reg3: reghdfe lemployment i1.p2p##i1.post [pweight=weight], a(i.siren i.nesc#i.year) cluster(siren) 
	estadd local firm "Y", replace 
	estadd local indyear "Y", replace  
    qui eststo reg4: reghdfe r1_pre_wsr i1.p2p##i1.post [pweight=weight], a(i.siren i.nesc#i.year) cluster(siren) 
	estadd local firm "Y", replace 
	estadd local indyear "Y", replace  
    qui eststo reg5: reghdfe dettefou_pre_wsr i1.p2p##i1.post [pweight=weight], a(i.siren i.nesc#i.year) cluster(siren) 
	estadd local firm "Y", replace 
	estadd local indyear "Y", replace  
    qui eststo reg6: reghdfe wc_no_dettefou_wsr i1.p2p##i1.post [pweight=weight], a(i.siren i.nesc#i.year) cluster(siren) 
	estadd local firm "Y", replace 
	estadd local indyear "Y", replace  

//----------------------------------------------------------------------------//
//                 STEP 8: EXPORT TABLE 9a TO LaTeX                             //
//----------------------------------------------------------------------------//

    esttab * using "$tables\real_firm_outcome_matched.tex", replace ///
        noomitted nobase fragment gap booktabs label nonote noobs nolines /// 
        b(%9.3f) drop(_cons) se(%9.3f) star(* 0.10 ** 0.05 *** 0.01) ///
        mtitles("Assets" "Tangible assets" "Employment" "Working capital" "WC: Payables" "WC: Others") ///
        order(1.p2p#1.post 1.post) ///
        varlabel(1.post "Post" 1.p2p#1.post `"FinTech $\times$ Post"') ///
        stats(firm indyear N r2, label(`"Firm FE"' `"Industry-Year FE"' `"\midrule N"' `"R-sq"') layout("\multicolumn{1}c{@}")) 

